import {BuildProfileBean, TaskConfig} from "../TaskBean";
import path from "path";
import fs from "fs";
import {Logger} from "../utils/Logger";
import {deleteExcessCommas, logNowTime, readFileContent, removeComments} from "../utils/CommonUtils";
import {hvigor} from "@ohos/hvigor";

export interface DeleteBuildTaskConfig extends TaskConfig {
    deleteDirRelativePath?: string[],
    projectBuildProfileRelativePath?: string
    deleteFile?: boolean
}

const TAG = ""


export function deleteBuildTask(projectPath: string, config?: DeleteBuildTaskConfig) {
    if (!config) {
        config = {debug: false, deleteDirRelativePath: []}
    }
    if (!config.deleteDirRelativePath) {
        config.deleteDirRelativePath = []
    }
    if (config.deleteFile == undefined) {
        config.deleteFile = true
    }
    const paths: string[] = []
    Logger.debug = config.debug ?? false
    Logger.info(TAG, "=======================deleteBuildPlugin=========================")
    const currentDirPath = path.resolve()

    const projectBuildPath = path.resolve(projectPath, 'build')
    Logger.info(TAG, 'projectPath:' + projectPath)
    Logger.info(TAG, 'projectBuildPath:' + projectBuildPath)

    paths.push(projectBuildPath)
    paths.push(path.resolve(projectPath, 'entry/build'))

    for (const relativeDir of config.deleteDirRelativePath) {
        const resBuildDirPath = path.resolve(projectPath, relativeDir)
        paths.push(resBuildDirPath)

        Logger.info(TAG, 'deleteDirRelativePath:' + resBuildDirPath)
    }
    const buildProfilePath = path.resolve(projectPath, 'build-profile.json5')
    let projectBuildProfileRelativePath = buildProfilePath
    if (config.projectBuildProfileRelativePath) {
        projectBuildProfileRelativePath = path.resolve(projectPath, config.projectBuildProfileRelativePath)
    }
    Logger.info(TAG, 'buildProfilePath:' + buildProfilePath)
    Logger.info(TAG, 'projectBuildProfileRelativePath:' + projectBuildProfileRelativePath)
    const module = getModuleBuildDirPath(projectBuildProfileRelativePath)
    Logger.info(TAG, module?.modules ?? [])
    if (module && module.modules && module.modules.length > 0) {
        for (const item of module.modules) {
            if (!item.srcPath) {
                continue
            }
            const buildPath = path.resolve(projectPath, item.srcPath, 'build')
            Logger.info(TAG, 'buildPath:' + buildPath)
            paths.push(buildPath)
        }
    }
    for (const item of paths) {
        checkAndDeletePath(item, config.deleteFile)
    }
    logNowTime(TAG)
}

function getModuleBuildDirPath(projectBuildProfileRelativePath: string): BuildProfileBean | undefined {
    if (!projectBuildProfileRelativePath || !fs.existsSync(projectBuildProfileRelativePath)) {
        return undefined
    }
    let content: string = readFileContent(projectBuildProfileRelativePath)
    content = removeComments(content)
    content = deleteExcessCommas(content)
    try {
        const buildProfile: BuildProfileBean = JSON.parse(content) as BuildProfileBean
        return buildProfile
    } catch (err) {
        console.info("请检查" + projectBuildProfileRelativePath + "的内容是不是正确的json数据")
        return undefined
    }
}

function checkAndDeletePath(path: string, deleteFile: boolean) {
    const isExist = fs.existsSync(path)
    Logger.info(TAG, "isExist:" + isExist + ",Path:" + path)
    if (!isExist) {
        return;
    }
    if (fs.statSync(path).isDirectory()) {
        removeDirSync(path, deleteFile)
    } else {
        fs.unlinkSync(path); // 删除文件
    }
}

function removeDirSync(dirPath: string, deleteFile: boolean) {
    let files = fs.readdirSync(dirPath);
    if (files.length > 0) {
        for (let i = 0; i < files.length; i++) {
            let filePath = path.join(dirPath, files[i]);
            if (fs.statSync(filePath).isDirectory()) {
                removeDirSync(filePath, deleteFile); // 递归删除子目录
            } else {
                if (deleteFile) {
                    fs.unlinkSync(filePath); // 删除文件
                }
            }
        }
    }
    if (deleteFile) {
        fs.rmdirSync(dirPath); // 删除空目录
    }
}